package com.example.demo.util;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


public class ImageWaterMatchUtil {
    //基于颜色特征判断图片是否含有水印
    public static boolean detectColorWatermark(String imagePath) {
        try {
            File file = new File(imagePath);
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            int totalPixels = width * height;
            int[] colorCount = new int[256 * 256 * 256];

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int argb = image.getRGB(x, y);
                    int red = (argb >> 16) & 0xff;
                    int green = (argb >> 8) & 0xff;
                    int blue = argb & 0xff;
                    int colorIndex = red * 256 * 256 + green * 256 + blue;
                    colorCount[colorIndex]++;
                }
            }

            int nonZeroCount = 0;
            for (int count : colorCount) {
                if (count > 0) {
                    nonZeroCount++;
                }
            }

            double colorDensity = (double) nonZeroCount / totalPixels;
            // 经验阈值，可根据实际情况调整
            return colorDensity < 0.1;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean detectOcrWatermark(String imagePath) {
        Tesseract tesseract = new Tesseract();
        try {
            File file = new File(imagePath);
            BufferedImage image = ImageIO.read(file);
            tesseract.setLanguage("chi_sim");
            String result = tesseract.doOCR(image);
            return!result.trim().isEmpty();
        } catch (IOException | TesseractException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        String imagePath = "D:/image/图片_009_20.png";
        boolean hasWatermarkOcr = detectOcrWatermark(imagePath);
        boolean hasWatermarkColor = detectColorWatermark(imagePath);
        if (hasWatermarkOcr||hasWatermarkColor) {
            System.out.println("图片可能含有水印");
        } else {
            System.out.println("图片可能不含有水印");
        }
    }
//    public static boolean detectWatermarkByML(String imagePath) throws IOException, InterruptedException {
//        int numRows = 28;
//        int numColumns = 28;
//        int outputNum = 2;
//        int batchSize = 100;
//        int rngSeed = 123;
//        int numEpochs = 10;
//
//        RecordReader recordReader = new CSVRecordReader();
//        recordReader.initialize(new FileSplit(new File("path/to/training/data.csv")));
//        DataSetIterator dataSetIterator = new RecordReaderDataSetIterator(recordReader, batchSize, numRows * numColumns, outputNum);
//        DataSet allData = dataSetIterator.next();
//        allData.shuffle(new Random(rngSeed));
//        SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
//        DataSet trainingData = testAndTrain.getTrain();
//        DataSet testData = testAndTrain.getTest();
//
//        DataNormalization normalizer = new NormalizerStandardize();
//        normalizer.fit(trainingData);
//        normalizer.transform(trainingData);
//        normalizer.transform(testData);
//
//        MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
//                .seed(rngSeed)
//                .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
//                .updater(new Sgd(0.1))
//                .l2(1e - 4)
//                .list()
//                .layer(0, new DenseLayer.Builder()
//                        .nIn(numRows * numColumns)
//                        .nOut(100)
//                        .activation(Activation.RELU)
//                        .weightInit(WeightInit.XAVIER)
//                        .build())
//                .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOGOD)
//                        .nIn(100)
//                        .nOut(outputNum)
//                        .activation(Activation.SOFTMAX)
//                        .weightInit(WeightInit.XAVIER)
//                        .build())
//                .build();
//
//        MultiLayerNetwork model = new MultiLayerNetwork(conf);
//        model.init();
//
//        for (int i = 0; i < numEpochs; i++) {
//            model.fit(trainingData);
//        }
//
//        INDArray output = model.output(testData.getFeatureMatrix());
//        System.out.println("Evaluate model....");
//        System.out.println(model.evaluate(testData));
//
//        // 预测新图片
//        // 这里需要将新图片处理成与训练数据相同格式的INDArray
//        // 假设newImageFeatureMatrix是处理好的新图片特征矩阵
//        INDArray newImageFeatureMatrix = null; // 实际需填充
//        normalizer.transform(newImageFeatureMatrix);
//        INDArray prediction = model.output(newImageFeatureMatrix);
//        int predictedLabel = prediction.argMax(1).getInt(0);
//        if (predictedLabel == 1) {
//            System.out.println("图片可能含有水印");
//        } else {
//            System.out.println("图片可能不含有水印");
//        }
//    }
}
